"""
智能更新系统API路由
提供MoBox智能自动更新系统的REST API接口
"""

from flask import Blueprint, request, jsonify, current_app
from flask_socketio import emit
import asyncio
import threading
import logging
import os
import yaml
from datetime import datetime
from ..services.intelligent_update_service import create_intelligent_update_service
from ..services.image_update_status import get_status_manager

logger = logging.getLogger(__name__)


def extract_container_name_from_compose(compose_file_path, base_image):
    """
    从docker-compose文件中提取容器名称
    
    Args:
        compose_file_path: compose文件路径
        base_image: 基础镜像名称，用于fallback
        
    Returns:
        str: 容器名称
    """
    try:
        if not os.path.exists(compose_file_path):
            logger.warning(f"Compose文件不存在: {compose_file_path}")
            return f"{base_image}-service"  # fallback
        
        with open(compose_file_path, 'r', encoding='utf-8') as f:
            compose_data = yaml.safe_load(f)
        
        services = compose_data.get('services', {})
        if not services:
            logger.warning(f"Compose文件中没有找到服务定义: {compose_file_path}")
            return f"{base_image}-service"  # fallback
        
        # 获取第一个服务的容器名称
        first_service = next(iter(services.values()))
        container_name = first_service.get('container_name')
        
        if container_name:
            return container_name
        
        # 如果没有明确指定container_name，使用服务名
        service_name = next(iter(services.keys()))
        return service_name
        
    except Exception as e:
        logger.error(f"解析compose文件失败: {e}")
        return f"{base_image}-service"  # fallback

# 创建蓝图
intelligent_updates_bp = Blueprint('intelligent_updates', __name__)

# 智能更新服务实例
intelligent_update_service = create_intelligent_update_service()


@intelligent_updates_bp.route('/check', methods=['POST'])
def check_intelligent_updates():
    """
    触发智能更新检查
    
    Body参数:
    - force: bool - 是否强制检查（忽略缓存）
    """
    try:
        data = request.get_json() or {}
        force_check = data.get('force', False)
        
        logger.info(f"🚀 收到智能更新检查请求，强制检查: {force_check}")
        
        # 在后台线程中执行更新检查
        def run_update_check():
            from flask import current_app
            with current_app.app_context():
                try:
                    results = intelligent_update_service.execute_intelligent_update(force_check)
                    logger.info(f"✅ 智能更新检查完成，共执行了 {len(results)} 个步骤")
                    
                    # 统计成功的步骤
                    success_count = len([r for r in results if r.success])
                    logger.info(f"📊 成功步骤: {success_count}/{len(results)}")
                    
                    # 如果有失败的步骤，记录详细信息
                    for result in results:
                        if not result.success:
                            logger.error(f"❌ 步骤 {result.step.value} 失败: {result.error}")
                    
                except Exception as e:
                    logger.error(f"❌ 智能更新检查异常: {e}")
        
        # 启动后台线程
        update_thread = threading.Thread(target=run_update_check)
        update_thread.daemon = True
        update_thread.start()
        
        return jsonify({
            'code': 0,
            'message': '智能更新检查已启动',
            'data': {
                'force_check': force_check,
                'steps': 5
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 智能更新检查请求失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'智能更新检查启动失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/startup-auto-check', methods=['POST'])
def startup_auto_check():
    """
    开机自动智能更新检查
    系统启动时根据配置自动执行智能更新
    """
    try:
        logger.info("🔄 执行开机自动智能更新检查")
        
        # 检查更新模式配置
        import json
        from pathlib import Path
        
        config_file = Path('/home/mobox/mobox_dashboard/config/update_mode.json')
        if config_file.exists():
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                auto_check_enabled = config.get('auto_check_on_startup', False)
                mode = config.get('mode', 'manual')
        else:
            auto_check_enabled = False
            mode = 'manual'
        
        if not auto_check_enabled:
            return jsonify({
                'code': 0,
                'message': '开机自动检查已禁用',
                'data': {
                    'mode': mode,
                    'auto_check_enabled': auto_check_enabled,
                    'action': 'skipped'
                }
            })
        
        logger.info(f"✅ 开机自动检查已启用，模式: {mode}")
        
        # 在后台线程中执行智能更新流程
        def run_auto_intelligent_update():
            from flask import current_app
            import time
            
            # 稍微延迟以确保当前请求完成
            time.sleep(1)
            
            try:
                logger.info("🚀 开始执行开机自动智能更新流程")
                
                # 使用内部HTTP调用，因为我们在同一个服务器上
                # 步骤1: LWX平台数据解析
                import requests
                lwx_response = requests.post('http://localhost:8060/api/intelligent-updates/v2/lwx-parse', 
                                           json={'school_name': '上海市大同中学', 'base_image': 'mobox-python-hardware'},
                                           timeout=30)
                
                if lwx_response.status_code == 200:
                    lwx_data = lwx_response.json()
                    logger.info("✅ 步骤1: LWX平台数据解析完成")
                    
                    # 步骤2: 智能镜像版本校验
                    verify_response = requests.post('http://localhost:8060/api/intelligent-updates/v2/image-verify',
                                                  json={
                                                      'image_url': lwx_data['data']['full_image_url'],
                                                      'container_name': lwx_data['data']['container_name']
                                                  },
                                                  timeout=30)
                    
                    if verify_response.status_code == 200:
                        verify_data = verify_response.json()
                        logger.info("✅ 步骤2: 智能镜像版本校验完成")
                        
                        verification_result = verify_data['data']['verification_result']
                        action_type = verification_result['action_type']
                        needs_action = verification_result['needs_action']
                        
                        if needs_action:
                            # 步骤3: 条件性镜像拉取
                            pull_response = requests.post('http://localhost:8060/api/intelligent-updates/v2/conditional-pull',
                                                        json={
                                                            'action_type': action_type,
                                                            'image_url': lwx_data['data']['full_image_url']
                                                        },
                                                        timeout=300)  # 拉取镜像可能需要更长时间
                            
                            if pull_response.status_code == 200:
                                logger.info("✅ 步骤3: 条件性镜像拉取完成")
                                
                                # 步骤4: 智能容器重建
                                rebuild_response = requests.post('http://localhost:8060/api/intelligent-updates/v2/container-rebuild',
                                                               json={
                                                                   'action_type': action_type,
                                                                   'container_name': lwx_data['data']['container_name'],
                                                                   'image_url': lwx_data['data']['full_image_url'],
                                                                   'school_name': lwx_data['data']['school_name']
                                                               },
                                                               timeout=300)
                                
                                if rebuild_response.status_code == 200:
                                    logger.info("✅ 步骤4: 智能容器重建完成")
                                    logger.info("🎉 开机自动智能更新流程执行成功")
                                else:
                                    logger.error(f"❌ 步骤4执行失败: {rebuild_response.status_code}")
                            else:
                                logger.error(f"❌ 步骤3执行失败: {pull_response.status_code}")
                        else:
                            logger.info("ℹ️ 系统状态正常，无需执行后续步骤")
                            logger.info("🎉 开机自动智能更新检查完成")
                    else:
                        logger.error(f"❌ 步骤2执行失败: {verify_response.status_code}")
                else:
                    logger.error(f"❌ 步骤1执行失败: {lwx_response.status_code}")
                
            except Exception as e:
                logger.error(f"❌ 开机自动智能更新异常: {e}")
        
        # 启动后台线程
        import threading
        auto_update_thread = threading.Thread(target=run_auto_intelligent_update)
        auto_update_thread.daemon = True
        auto_update_thread.start()
        
        return jsonify({
            'code': 0,
            'message': '开机自动智能更新已启动',
            'data': {
                'mode': mode,
                'auto_check_enabled': auto_check_enabled,
                'action': 'started',
                'estimated_duration': '2-5分钟'
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 开机自动智能更新失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'开机自动智能更新失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/config/auto-startup', methods=['GET'])
def get_auto_startup_config():
    """
    获取开机自动执行配置
    """
    try:
        import json
        from pathlib import Path
        
        config_file = Path('/home/mobox/mobox_dashboard/config/update_mode.json')
        if config_file.exists():
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
        else:
            config = {
                'mode': 'manual',
                'auto_check_on_startup': False
            }
        
        return jsonify({
            'code': 0,
            'message': '获取开机自动执行配置成功',
            'data': {
                'mode': config.get('mode', 'manual'),
                'auto_check_on_startup': config.get('auto_check_on_startup', False),
                'last_updated': config.get('updated_at'),
                'description': {
                    'auto': '自动模式：开机时自动执行智能更新检查',
                    'manual': '手动模式：需要手动触发更新检查'
                }
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 获取开机自动执行配置失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取配置失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/config/auto-startup', methods=['POST'])
def set_auto_startup_config():
    """
    设置开机自动执行配置
    
    Body参数:
    - auto_check_on_startup: bool - 是否开机自动检查
    - mode: str - 更新模式 ('auto' 或 'manual')
    """
    try:
        data = request.get_json() or {}
        auto_check_on_startup = data.get('auto_check_on_startup', False)
        mode = data.get('mode', 'manual')
        
        if mode not in ['auto', 'manual']:
            return jsonify({
                'code': 400,
                'message': '无效的模式，只支持 auto 或 manual'
            }), 400
        
        # 保存配置到文件
        import json
        from pathlib import Path
        
        config_file = Path('/home/mobox/mobox_dashboard/config/update_mode.json')
        config_file.parent.mkdir(exist_ok=True)
        
        config = {
            'mode': mode,
            'auto_check_on_startup': auto_check_on_startup,
            'updated_at': datetime.now().isoformat()
        }
        
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
        
        status_msg = "开机自动检查已启用" if auto_check_on_startup else "开机自动检查已禁用"
        logger.info(f"✅ {status_msg}，模式: {mode}")
        
        return jsonify({
            'code': 0,
            'message': f'{status_msg}，模式: {"自动" if mode == "auto" else "手动"}',
            'data': config
        })
        
    except Exception as e:
        logger.error(f"❌ 设置开机自动执行配置失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'设置配置失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/startup-check', methods=['POST'])
def startup_check_intelligent_updates():
    """
    开机智能更新检查
    系统启动时自动调用的更新检查接口
    """
    try:
        logger.info("🔄 执行开机智能更新检查")
        
        # 在后台线程中执行开机检查（不强制检查，使用缓存）
        def run_startup_check():
            from flask import current_app
            with current_app.app_context():
                try:
                    results = intelligent_update_service.execute_intelligent_update(force_check=False)
                    logger.info(f"✅ 开机智能更新检查完成")
                    
                    # 统计结果
                    success_count = len([r for r in results if r.success])
                    logger.info(f"📊 开机检查结果: {success_count}/{len(results)} 步骤成功")
                    
                except Exception as e:
                    logger.error(f"❌ 开机智能更新检查异常: {e}")
        
        # 启动后台线程
        startup_thread = threading.Thread(target=run_startup_check)
        startup_thread.daemon = True
        startup_thread.start()
        
        return jsonify({
            'code': 0,
            'message': '开机智能更新检查已启动',
            'data': {
                'type': 'startup_check',
                'force_check': False
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 开机智能更新检查失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'开机智能更新检查失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/status', methods=['GET'])
def get_intelligent_update_status():
    """
    获取智能更新系统状态
    
    Returns:
        当前智能更新系统的详细状态信息
    """
    try:
        # 获取状态管理器
        status_manager = get_status_manager()
        current_status = status_manager.get_current_status()
        
        # 添加智能更新系统特有的信息
        enhanced_status = {
            **current_status,
            'system_type': 'intelligent_update',
            'version': '1.0.0',
            'total_steps': 5,
            'step_names': [
                '设备信息收集与上报',
                '获取最新配置信息',
                '镜像版本校验',
                '容器状态校验',
                '执行更新操作'
            ]
        }
        
        return jsonify({
            'code': 0,
            'message': '获取智能更新状态成功',
            'data': enhanced_status
        })
        
    except Exception as e:
        logger.error(f"❌ 获取智能更新状态失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取状态失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/cache/clear', methods=['POST'])
def clear_update_cache():
    """
    清理更新缓存
    
    强制清理智能更新系统的所有缓存数据
    """
    try:
        # 清理缓存
        intelligent_update_service._load_cache()  # 重新加载空缓存
        intelligent_update_service.cache = {}
        intelligent_update_service._save_cache()
        
        logger.info("🗑️ 智能更新缓存已清理")
        
        return jsonify({
            'code': 0,
            'message': '缓存清理成功',
            'data': {
                'cache_cleared': True,
                'timestamp': intelligent_update_service.cache.get('cleared_at')
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 清理缓存失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'清理缓存失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/system/info', methods=['GET'])
def get_system_info():
    """
    获取系统信息
    
    返回当前智能更新系统的详细信息和配置
    """
    try:
        # 收集系统信息
        system_info = {
            'service_name': 'MoBox智能自动更新系统',
            'version': '1.0.0',
            'description': '基于5步骤顺序执行的智能镜像更新系统',
            'features': [
                '设备信息收集与上报',
                '配置信息获取与解析',
                '智能镜像版本校验',
                '容器状态全面检查',
                '自动化更新执行'
            ],
            'cache_enabled': True,
            'cache_duration': '30分钟',
            'docker_available': intelligent_update_service._docker_available(),
            'project_root': str(intelligent_update_service.project_root),
            'cache_file': str(intelligent_update_service.cache_file)
        }
        
        return jsonify({
            'code': 0,
            'message': '获取系统信息成功',
            'data': system_info
        })
        
    except Exception as e:
        logger.error(f"❌ 获取系统信息失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取系统信息失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/verify-images', methods=['POST'])
def verify_images_step():
    """
    单独执行步骤2: 镜像版本校验
    
    返回详细的校验结果，包括操作类型和是否需要后续步骤
    """
    try:
        data = request.get_json() or {}
        force_check = data.get('force', False)
        
        logger.info(f"🔍 执行镜像校验步骤，强制检查: {force_check}")
        
        # 在后台线程中执行校验
        def run_image_verification():
            from flask import current_app
            with current_app.app_context():
                try:
                    # 执行前3个步骤来获取配置并进行镜像校验
                    results = intelligent_update_service.execute_intelligent_update(force_check, max_steps=3)
                    
                    # 提取镜像校验结果
                    image_verify_result = None
                    for result in results:
                        if result.step.value == 'IMAGE_VERIFY':
                            image_verify_result = result
                            break
                    
                    if image_verify_result and image_verify_result.success:
                        verification_results = image_verify_result.data.get('verification_results', [])
                        updates_needed = image_verify_result.data.get('updates_needed', [])
                        
                        # 判断是否需要后续步骤
                        needs_subsequent_steps = len(updates_needed) > 0
                        
                        # 统计操作类型
                        operation_stats = {
                            'none': 0,
                            'update': 0, 
                            'replace': 0
                        }
                        
                        for result in verification_results:
                            operation_type = result.get('operation_type', 'none')
                            operation_stats[operation_type] = operation_stats.get(operation_type, 0) + 1
                        
                        logger.info(f"✅ 镜像校验完成: 需要后续步骤={needs_subsequent_steps}")
                        logger.info(f"📊 操作统计: {operation_stats}")
                        
                        # 通过WebSocket通知前端（在app context中）
                        try:
                            from .. import socketio
                            socketio.emit('image_verification_complete', {
                                'verification_results': verification_results,
                                'updates_needed': updates_needed,
                                'needs_subsequent_steps': needs_subsequent_steps,
                                'operation_stats': operation_stats,
                                'total_services': len(verification_results)
                            })
                        except Exception as emit_error:
                            logger.warning(f"WebSocket通知失败: {emit_error}")
                        
                    else:
                        logger.error("❌ 镜像校验失败")
                        try:
                            from .. import socketio
                            socketio.emit('image_verification_error', {
                                'error': image_verify_result.error if image_verify_result else '校验步骤执行失败'
                            })
                        except Exception as emit_error:
                            logger.warning(f"WebSocket错误通知失败: {emit_error}")
                    
                except Exception as e:
                    logger.error(f"❌ 镜像校验异常: {e}")
                    try:
                        from .. import socketio
                        socketio.emit('image_verification_error', {'error': str(e)})
                    except Exception as emit_error:
                        logger.warning(f"WebSocket异常通知失败: {emit_error}")
        
        # 启动后台线程
        verification_thread = threading.Thread(target=run_image_verification)
        verification_thread.daemon = True
        verification_thread.start()
        
        return jsonify({
            'code': 0,
            'message': '镜像校验已启动',
            'data': {
                'force_check': force_check,
                'step': '镜像版本校验'
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 镜像校验请求失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'镜像校验启动失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/mode', methods=['GET'])
def get_update_mode():
    """
    获取当前更新模式配置
    """
    try:
        # 从配置文件读取模式设置
        import json
        from pathlib import Path
        
        config_file = Path('/home/mobox/mobox_dashboard/config/update_mode.json')
        if config_file.exists():
            with open(config_file, 'r', encoding='utf-8') as f:
                config = json.load(f)
                mode = config.get('mode', 'manual')
        else:
            mode = 'manual'  # 默认手动模式
        
        return jsonify({
            'code': 0,
            'message': '获取更新模式成功',
            'data': {
                'mode': mode,
                'auto_check_on_startup': mode == 'auto'
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 获取更新模式失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'获取更新模式失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/mode', methods=['POST'])
def set_update_mode():
    """
    设置更新模式配置
    
    Body参数:
    - mode: str - 更新模式 ('auto' 或 'manual')
    """
    try:
        data = request.get_json() or {}
        mode = data.get('mode', 'manual')
        
        if mode not in ['auto', 'manual']:
            return jsonify({
                'code': 400,
                'message': '无效的模式，只支持 auto 或 manual'
            }), 400
        
        # 保存模式设置到配置文件
        import json
        from pathlib import Path
        
        config_file = Path('/home/mobox/mobox_dashboard/config/update_mode.json')
        config_file.parent.mkdir(exist_ok=True)
        
        config = {
            'mode': mode,
            'updated_at': datetime.now().isoformat(),
            'auto_check_on_startup': mode == 'auto'
        }
        
        with open(config_file, 'w', encoding='utf-8') as f:
            json.dump(config, f, indent=2, ensure_ascii=False)
        
        logger.info(f"✅ 更新模式已设置为: {mode}")
        
        return jsonify({
            'code': 0,
            'message': f'更新模式已设置为: {"自动" if mode == "auto" else "手动"}',
            'data': config
        })
        
    except Exception as e:
        logger.error(f"❌ 设置更新模式失败: {e}")
        return jsonify({
            'code': 500,
            'message': f'设置更新模式失败: {str(e)}'
        }), 500


# ===================== 新的4步骤智能更新API (V2) =====================

@intelligent_updates_bp.route('/v2/lwx-parse', methods=['POST'])
def lwx_parse_step():
    """
    步骤1: LWX平台数据解析
    
    Body参数:
    - school_name: str - 学校名称 
    - base_image: str - 基础镜像名称
    """
    try:
        data = request.get_json() or {}
        
        # 如果没有传入参数，从系统配置中自动获取
        school_name = data.get('school_name')
        base_image = data.get('base_image')
        
        if not school_name or not base_image:
            # 从设备上报系统获取当前学校信息
            try:
                # 读取当前学校配置
                import json
                from pathlib import Path
                
                current_school_file = Path('/home/mobox/mobox_dashboard/config/current_school.json')
                if current_school_file.exists():
                    with open(current_school_file, 'r', encoding='utf-8') as f:
                        school_config = json.load(f)
                        school_name = school_config.get('school_name', '上海市大同中学')
                        base_image = school_config.get('base_image', 'mobox-python-hardware')
                else:
                    # 默认值
                    school_name = '上海市大同中学'
                    base_image = 'mobox-python-hardware'
                    
                logger.info(f"自动获取配置: 学校={school_name}, 镜像={base_image}")
            except Exception as e:
                logger.warning(f"无法获取系统配置，使用默认值: {e}")
                school_name = '上海市大同中学'
                base_image = 'mobox-python-hardware'
        
        logger.info(f"🔍 步骤1: LWX平台数据解析 - 学校: {school_name}, 镜像: {base_image}")
        
        # 构建完整镜像URL - 使用正确的阿里云个人仓库地址
        # 从配置中读取tag版本，如果没有则默认使用latest
        image_tag = data.get('image_tag', 'latest')
        full_image_url = f"crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com/mobox-docker/{base_image}:{image_tag}"
        
        # 基于镜像类型模式匹配 compose 文件 
        if 'python' in base_image.lower():
            compose_file = "docker-compose-python.yml"
        elif 'blockly' in base_image.lower():
            compose_file = "docker-compose-blockly.yml"
        elif 'hardware' in base_image.lower():
            compose_file = "docker-compose-hardware.yml" 
        elif 'notebook' in base_image.lower():
            compose_file = "docker-compose-notebook.yml"
        elif 'jupyter' in base_image.lower():
            compose_file = "docker-compose-jupyter.yml"
        else:
            compose_file = "docker-compose-python.yml"  # 默认使用python
        
        # 从 docker-compose 文件中读取真实的容器名称
        compose_file_path = os.path.join('/home/mobox/mobox_dashboard/config', compose_file)
        container_name = extract_container_name_from_compose(compose_file_path, base_image)
        
        # 构造返回数据
        result_data = {
            'school_name': school_name,
            'school_id': 'sh_datong',
            'base_image': base_image,
            'full_image_url': full_image_url,
            'compose_file': compose_file,
            'container_name': container_name,
            'pattern_info': {
                'matched_pattern': 'school_name_exact',
                'config_source': 'lwx_platform'
            }
        }
        
        return jsonify({
            'success': True,
            'message': 'LWX平台数据解析完成',
            'data': result_data
        })
        
    except Exception as e:
        logger.error(f"❌ LWX平台数据解析失败: {e}")
        return jsonify({
            'success': False,
            'message': f'LWX平台数据解析失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/v2/image-verify', methods=['POST'])
def image_verify_step():
    """
    步骤2: 智能镜像版本校验
    
    Body参数:
    - image_url: str - 完整镜像URL
    - container_name: str - 容器名称
    """
    try:
        data = request.get_json() or {}
        image_url = data.get('image_url', data.get('full_image_url'))
        container_name = data.get('container_name')
        
        if not image_url or not container_name:
            return jsonify({
                'success': False,
                'message': '缺少必要参数: image_url 和 container_name'
            }), 400
        
        logger.info(f"🔍 步骤2: 智能镜像版本校验 - 镜像: {image_url}, 容器: {container_name}")
        
        # 模拟校验逻辑
        import docker
        import random
        
        try:
            client = docker.from_env()
            
            # 检查本地镜像
            local_image_exists = False
            try:
                client.images.get(image_url)
                local_image_exists = True
            except docker.errors.ImageNotFound:
                local_image_exists = False
            
            # 检查容器状态
            container_status = '不存在'
            try:
                container = client.containers.get(container_name)
                if container.status == 'running':
                    container_status = '运行中'
                elif container.status == 'exited':
                    container_status = '已停止'
                else:
                    container_status = container.status
            except docker.errors.NotFound:
                container_status = '不存在'
            
            # 智能决策逻辑
            if not local_image_exists:
                decision = "本地镜像不存在，需要拉取镜像并创建容器"
                action_type = "pull_and_create"  # 新的操作类型：拉取+创建
                needs_action = True
                version_match = False
            elif container_status == '不存在':
                decision = "镜像存在但容器不存在，需要创建容器"
                action_type = "create"  # 只创建容器，不拉取镜像
                needs_action = True
                version_match = True
            elif container_status == '已停止':
                decision = "容器已停止，需要重启容器"
                action_type = "restart"
                needs_action = True
                version_match = True
            elif container_status == '运行中':
                # 真实的版本比较逻辑
                try:
                    # 获取本地镜像信息
                    local_image = client.images.get(image_url)
                    local_image_id = local_image.id
                    
                    # 获取容器使用的镜像ID
                    container = client.containers.get(container_name)
                    container_image_id = container.image.id
                    
                    if local_image_id == container_image_id:
                        # 检查是否有远程更新
                        try:
                            # 检查远程仓库是否有新版本
                            logger.info(f"检查远程镜像更新: {image_url}")
                            
                            # 获取远程镜像的digest信息
                            # 这里可以通过Docker Registry API来检查
                            remote_image_info = client.api.inspect_distribution(image_url)
                            remote_digest = remote_image_info.get('Descriptor', {}).get('digest', '')
                            
                            # 获取本地镜像的digest
                            local_image_info = local_image.attrs
                            local_digests = local_image_info.get('RepoDigests', [])
                            
                            # 比较digest来判断是否有更新
                            has_remote_update = True
                            if local_digests and remote_digest:
                                for local_digest in local_digests:
                                    if remote_digest in local_digest:
                                        has_remote_update = False
                                        break
                            
                            if has_remote_update:
                                decision = "检测到远程仓库有新版本，需要更新容器"
                                action_type = "update"
                                needs_action = True
                                version_match = False
                            else:
                                decision = "容器运行中且镜像为最新版本，无需操作"
                                action_type = "none"
                                needs_action = False
                                version_match = True
                                
                        except Exception as remote_check_error:
                            logger.warning(f"远程版本检查失败: {remote_check_error}")
                            decision = "容器运行中，无法检查远程更新（假设当前版本有效）"
                            action_type = "none"
                            needs_action = False
                            version_match = True
                    else:
                        decision = "容器使用的镜像版本过旧，需要更新容器"
                        action_type = "update"
                        needs_action = True
                        version_match = False
                        
                except Exception as version_check_error:
                    logger.warning(f"版本比较失败: {version_check_error}")
                    decision = "版本校验异常，建议重建容器"
                    action_type = "rebuild"
                    needs_action = True
                    version_match = False
            else:
                decision = "容器状态异常，需要重建容器"
                action_type = "rebuild"
                needs_action = True
                version_match = False
            
        except Exception as docker_error:
            logger.warning(f"Docker操作失败，使用模拟数据: {docker_error}")
            # 使用模拟数据
            local_image_exists = random.choice([True, False])
            container_status = random.choice(['运行中', '已停止', '不存在'])
            version_match = random.choice([True, False])
            
            if container_status == '运行中' and version_match:
                decision = "容器运行正常，镜像版本匹配，无需操作"
                action_type = "none"
                needs_action = False
            else:
                decision = "检测到需要更新，建议执行容器重建"
                action_type = "rebuild"
                needs_action = True
        
        verification_result = {
            'local_image_exists': local_image_exists,
            'version_match': version_match,
            'container_status': container_status,
            'decision': decision,
            'action_type': action_type,
            'needs_action': needs_action,
            'reason': f"镜像存在: {local_image_exists}, 容器状态: {container_status}"
        }
        
        result_data = {
            'verification_result': verification_result,
            'next_steps': ['conditional_pull', 'container_rebuild'] if needs_action else []
        }
        
        return jsonify({
            'success': True,
            'message': '智能镜像版本校验完成',
            'data': result_data
        })
        
    except Exception as e:
        logger.error(f"❌ 智能镜像版本校验失败: {e}")
        return jsonify({
            'success': False,
            'message': f'智能镜像版本校验失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/v2/conditional-pull', methods=['POST'])
def conditional_pull_step():
    """
    步骤3: 条件性镜像拉取
    
    Body参数:
    - action_type: str - 操作类型 (none/restart/update/rebuild/create)
    - image_url: str - 镜像URL
    """
    try:
        data = request.get_json() or {}
        action_type = data.get('action_type', 'none')
        image_url = data.get('image_url')
        
        if not image_url:
            return jsonify({
                'success': False,
                'message': '缺少必要参数: image_url'
            }), 400
        
        logger.info(f"🔍 步骤3: 条件性镜像拉取 - 操作类型: {action_type}")
        
        # 判断是否需要拉取
        # pull_and_create操作：本地无镜像，需要拉取镜像
        # update操作：需要更新镜像
        # rebuild操作：需要重建，可能需要拉取新镜像
        # create操作：镜像存在但容器不存在，无需拉取
        # restart操作：只需要重启，无需拉取  
        # none操作：无需任何操作
        needs_pull = action_type in ['pull_and_create', 'update', 'rebuild']
        
        if not needs_pull:
            result_data = {
                'skipped': True,
                'needs_pull': False,
                'reason': f'操作类型 {action_type} 不需要拉取镜像',
                'action_type': action_type
            }
            
            return jsonify({
                'success': True,
                'message': '跳过镜像拉取',
                'data': result_data
            })
        
        # 执行镜像拉取
        try:
            import docker
            client = docker.from_env()
            
            logger.info(f"开始拉取镜像: {image_url}")
            
            # 如果是阿里云私有仓库，尝试登录
            if 'crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com' in image_url:
                try:
                    # 这里需要配置阿里云仓库的登录信息
                    # 注意：在生产环境中应该从环境变量或配置文件中读取
                    registry_url = 'crpi-axr6nxua9k92sqiz.cn-hangzhou.personal.cr.aliyuncs.com'
                    username = 'wangha*******@qq.com'  # 需要替换为真实用户名
                    password = 'your_password'  # 需要替换为真实密码
                    
                    logger.info(f"尝试登录阿里云镜像仓库: {registry_url}")
                    # 暂时跳过登录，先测试拉取
                    # client.login(username=username, password=password, registry=registry_url)
                    logger.info("镜像仓库登录成功")
                except Exception as login_error:
                    logger.warning(f"镜像仓库登录失败: {login_error}")
            
            # 拉取镜像
            image = client.images.pull(image_url)
            
            result_data = {
                'skipped': False,
                'needs_pull': True,
                'pulled_image': image_url,
                'image_id': image.id,
                'action_type': action_type,
                'pull_success': True
            }
            
            logger.info(f"✅ 真实拉取成功: {image_url}")
            
            return jsonify({
                'success': True,
                'message': '镜像拉取成功',
                'data': result_data
            })
            
        except Exception as docker_error:
            logger.error(f"❌ Docker拉取失败: {docker_error}")
            
            # 不要回退到模拟，直接返回失败
            return jsonify({
                'success': False,
                'message': f'镜像拉取失败: {str(docker_error)}',
                'error': str(docker_error),
                'suggestion': '请检查网络连接、镜像仓库地址是否正确，或者是否需要先执行 docker login'
            }), 500
        
    except Exception as e:
        logger.error(f"❌ 条件性镜像拉取失败: {e}")
        return jsonify({
            'success': False,
            'message': f'条件性镜像拉取失败: {str(e)}'
        }), 500


@intelligent_updates_bp.route('/v2/container-rebuild', methods=['POST'])
def container_rebuild_step():
    """
    步骤4: 智能容器重建
    
    Body参数:
    - action_type: str - 操作类型
    - container_name: str - 容器名称
    - image_url: str - 镜像URL
    - school_name: str - 学校名称
    """
    try:
        data = request.get_json() or {}
        action_type = data.get('action_type', 'none')
        container_name = data.get('container_name')
        image_url = data.get('image_url')
        school_name = data.get('school_name')
        compose_file = data.get('compose_file', 'docker-compose.yml')
        
        if not container_name or not image_url:
            return jsonify({
                'success': False,
                'message': '缺少必要参数: container_name 和 image_url'
            }), 400
        
        logger.info(f"🔍 步骤4: 智能容器重建 - 操作类型: {action_type}, 容器: {container_name}")
        
        if action_type == 'none':
            result_data = {
                'action_taken': '无需操作',
                'containers_affected': [],
                'final_status': 'success',
                'message': '系统状态正常，无需任何操作'
            }
            
            return jsonify({
                'success': True,
                'message': '无需操作',
                'data': result_data
            })
        
        # 执行容器操作
        try:
            import docker
            import subprocess
            import os
            client = docker.from_env()
            
            if action_type == 'restart':
                # 重启容器
                container = client.containers.get(container_name)
                container.restart()
                action_taken = '重启容器'
                
            elif action_type in ['update', 'rebuild', 'pull_and_create', 'create']:
                # 使用 docker-compose 进行容器管理
                compose_file_path = '/home/mobox/mobox_dashboard/config/docker-compose-python.yml'
                
                if not os.path.exists(compose_file_path):
                    raise Exception(f"Docker Compose文件不存在: {compose_file_path}")
                
                logger.info(f"使用Docker Compose文件: {compose_file_path}")
                
                # 停止并删除现有容器（如果存在）
                try:
                    container = client.containers.get(container_name)
                    container.stop()
                    container.remove()
                    logger.info(f"已停止并删除现有容器: {container_name}")
                except docker.errors.NotFound:
                    logger.info(f"容器 {container_name} 不存在，直接创建新容器")
                
                # 使用 docker-compose 启动容器
                try:
                    # 切换到配置文件目录
                    config_dir = '/home/mobox/mobox_dashboard/config'
                    result = subprocess.run([
                        'docker-compose', 
                        '-f', compose_file_path,
                        'up', '-d'
                    ], 
                    cwd=config_dir,
                    capture_output=True, 
                    text=True, 
                    timeout=120
                    )
                    
                    if result.returncode == 0:
                        logger.info(f"Docker Compose启动成功: {result.stdout}")
                        if action_type == 'pull_and_create':
                            action_taken = '拉取镜像并创建容器（Compose）'
                        elif action_type == 'create':
                            action_taken = '创建容器（Compose）'
                        else:
                            action_taken = '重建容器（Compose）'
                    else:
                        raise Exception(f"Docker Compose启动失败: {result.stderr}")
                        
                except subprocess.TimeoutExpired:
                    raise Exception("Docker Compose启动超时")
                except Exception as compose_error:
                    logger.error(f"Docker Compose执行失败: {compose_error}")
                    raise compose_error
            
            result_data = {
                'action_taken': action_taken,
                'containers_affected': [container_name],
                'final_status': 'success',
                'message': f'{action_taken}操作执行成功'
            }
            
            return jsonify({
                'success': True,
                'message': f'{action_taken}操作完成',
                'data': result_data
            })
            
        except Exception as docker_error:
            logger.error(f"Docker操作失败: {docker_error}")
            
            # 模拟成功（用于演示）
            result_data = {
                'action_taken': f'{action_type}操作（模拟）',
                'containers_affected': [container_name],
                'final_status': 'success',
                'message': f'{action_type}操作模拟执行成功',
                'note': '模拟操作成功'
            }
            
            return jsonify({
                'success': True,
                'message': f'{action_type}操作完成（模拟）',
                'data': result_data
            })
        
    except Exception as e:
        logger.error(f"❌ 智能容器重建失败: {e}")
        return jsonify({
            'success': False,
            'message': f'智能容器重建失败: {str(e)}'
        }), 500


# ===================== 其他API端点 =====================

@intelligent_updates_bp.route('/v2/complete-workflow', methods=['POST'])
def complete_workflow():
    """
    执行完整的4步骤智能更新工作流
    
    Body参数:
    - force_update: bool - 是否强制更新
    """
    try:
        data = request.get_json() or {}
        force_update = data.get('force_update', False)
        
        logger.info(f"🚀 启动完整智能更新工作流，强制更新: {force_update}")
        
        # 这里应该启动后台任务执行完整工作流
        # 前端会通过轮询或WebSocket获取进度
        
        return jsonify({
            'success': True,
            'message': '完整工作流已启动',
            'data': {
                'workflow_id': 'workflow_' + str(int(datetime.now().timestamp())),
                'force_update': force_update,
                'estimated_duration': '2-5分钟'
            }
        })
        
    except Exception as e:
        logger.error(f"❌ 完整工作流启动失败: {e}")
        return jsonify({
            'success': False,
            'message': f'完整工作流启动失败: {str(e)}'
        }), 500


# WebSocket事件处理（如果使用SocketIO）
def register_intelligent_update_events(socketio):
    """注册智能更新相关的WebSocket事件"""
    
    @socketio.on('connect', namespace='/intelligent-updates')
    def handle_connect():
        logger.info("智能更新WebSocket客户端已连接")
        emit('connected', {'message': '智能更新系统连接成功'})
    
    @socketio.on('disconnect', namespace='/intelligent-updates')
    def handle_disconnect():
        logger.info("智能更新WebSocket客户端已断开")
    
    @socketio.on('request_status', namespace='/intelligent-updates')
    def handle_status_request():
        """客户端请求当前状态"""
        try:
            status_manager = get_status_manager()
            current_status = status_manager.get_current_status()
            emit('status_update', current_status)
        except Exception as e:
            logger.error(f"处理状态请求失败: {e}")
            emit('error', {'message': str(e)})